<template>
  <div class="health-container">
    <!-- 添加页面标题区域 -->
    <div class="page-header">
      <h2>健康档案</h2>
      <p class="subtitle">管理我的健康档案</p>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="openDialog('add')" style="margin-bottom: 20px;">添加档案信息</el-button>
    </div>

    <!-- 信息列表 -->
    <el-row :gutter="20" class="health-list">
      <el-col :span="8" v-for="health in healths" :key="health.id">
        <el-card class="health-card" shadow="hover">
          <div class="health-header">
            <h2 class="health-title">体检日期：{{ formatDate(health.checkDate) }}</h2>
          </div>
          <div class="health-content">
            <p class="health-info"><strong>身高：</strong> {{ health.height }} cm</p>
            <p class="health-info"><strong>体重：</strong> {{ health.weight }} kg</p>
            <p class="health-info"><strong>血压：</strong>
              {{ health.bloodPressureSystolic }}/{{ health.bloodPressureDiastolic }} mmHg</p>
            <p class="health-info"><strong>心率：</strong> {{ health.heartRate }} 次/分钟</p>
            <p class="health-info"><strong>血型：</strong> {{ health.bloodType }}</p>
            <p class="health-info"><strong>血糖：</strong> {{ health.bloodGlucose }} mmol/L</p>
            <p class="health-info"><strong>胆固醇：</strong> {{ health.cholesterol }} mmol/L</p>
            <p class="health-info"><strong>甘油三酯：</strong> {{ health.triglycerides }} mmol/L</p>
            <p class="health-info"><strong>肝功能：</strong> {{ health.liverFunction }}</p>
            <p class="health-info"><strong>肾功能：</strong> {{ health.kidneyFunction }}</p>
            <p class="health-info"><strong>其他发现：</strong> {{ health.otherFindings }}</p>
            <p class="health-info"><strong>医生建议：</strong> {{ health.doctorAdvice }}</p>
          </div>
          <div class="health-footer">
            <el-button type="text" @click="viewDetail(health)">健康咨询</el-button>
            <el-button type="text" @click="openDialog('edit',health)">编辑</el-button>
            <el-button type="text" @click="delHealth(health)">删除</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加档案信息的弹出框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%">

      <el-form :model="healthForm" ref="healthForm" label-width="140px" style="padding-right: 100px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="体检日期" prop="checkDate" :rules="[{ required: true, message: '体检日期不能为空' }]">
              <el-date-picker v-model="healthForm.checkDate" type="date" placeholder="请选择体检日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身高(cm)" prop="height" :rules="[{ required: true, message: '身高不能为空' }]">
              <el-input v-model="healthForm.height" placeholder="请输入身高"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="体重(kg)" prop="weight" :rules="[{ required: true, message: '体重不能为空' }]">
              <el-input v-model="healthForm.weight" placeholder="请输入体重"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收缩压(mmHg)" prop="bloodPressureSystolic"
                          :rules="[{ required: true, message: '收缩压不能为空' }]">
              <el-input v-model="healthForm.bloodPressureSystolic" placeholder="请输入收缩压"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="舒张压(mmHg)" prop="bloodPressureDiastolic"
                          :rules="[{ required: true, message: '舒张压不能为空' }]">
              <el-input v-model="healthForm.bloodPressureDiastolic" placeholder="请输入舒张压"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="心率(次/分钟)" prop="heartRate" :rules="[{ required: true, message: '心率不能为空' }]">
              <el-input v-model="healthForm.heartRate" placeholder="请输入心率"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="血型" prop="bloodType" :rules="[{ required: true, message: '血型不能为空' }]">
              <el-input v-model="healthForm.bloodType" placeholder="请输入血型"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="血糖(mmol/L)" prop="bloodGlucose"
                          :rules="[{ required: true, message: '血糖不能为空' }]">
              <el-input v-model="healthForm.bloodGlucose" placeholder="请输入血糖"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="胆固醇(mmol/L)" prop="cholesterol"
                          :rules="[{ required: true, message: '胆固醇不能为空' }]">
              <el-input v-model="healthForm.cholesterol" placeholder="请输入胆固醇"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甘油三酯(mmol/L)" prop="triglycerides"
                          :rules="[{ required: true, message: '甘油三酯不能为空' }]">
              <el-input v-model="healthForm.triglycerides" placeholder="请输入甘油三酯"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="肝功能" prop="liverFunction" :rules="[{ required: true, message: '肝功能不能为空' }]">
              <el-input v-model="healthForm.liverFunction" placeholder="请输入肝功能"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="肾功能" prop="kidneyFunction" :rules="[{ required: true, message: '肾功能不能为空' }]">
              <el-input v-model="healthForm.kidneyFunction" placeholder="请输入肾功能"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="其他发现" prop="otherFindings"
                          :rules="[{ required: true, message: '其他发现不能为空' }]">
              <el-input type="textarea" v-model="healthForm.otherFindings" placeholder="请输入其他发现"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="医生建议" prop="doctorAdvice"
                          :rules="[{ required: true, message: '医生建议不能为空' }]">
              <el-input type="textarea" v-model="healthForm.doctorAdvice" placeholder="请输入医生建议"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveHealth">保存</el-button>
      </span>
    </el-dialog>

    <el-drawer
        size="50%"
        title="中医文化"
        :with-header="false"
        :visible.sync="drawer">
      <ChatView ref="chat"></ChatView>
    </el-drawer>

  </div>
</template>

<script>
import api from "@/api";
import {formatDate} from "@/utils/date";
import {getCache} from "@/utils/useCache";
import ChatView from "@/components/ChatView.vue";

export default {
  name: "HomeView",
  components: {
    ChatView
  },
  data() {
    return {
      drawer: false,
      healths: [], // 信息列表数据
      dialogVisible: false, // 弹出框是否显示
      dialogTitle: "", // 弹出框标题
      healthForm: {
        checkDate: null,
        height: null,
        weight: null,
        bloodPressureSystolic: null,
        bloodPressureDiastolic: null,
        heartRate: null,
        bloodType: null,
        bloodGlucose: null,
        cholesterol: null,
        triglycerides: null,
        liverFunction: null,
        kidneyFunction: null,
        otherFindings: null,
        doctorAdvice: null,
        userId: getCache('USERINFO').id,
      }, // 健康档案表单数据
      currentAction: "", // 当前操作类型（add/edit）
      user: getCache('USERINFO'),
    };
  },
  mounted() {
    this.fetchHealth();
  },
  methods: {
    formatDate,
    // 获取信息列表
    async fetchHealth() {
      const response = await api.health.healthList();
      const mockData = response.data.data;
      this.healths = mockData.filter((item) =>
          item.userId === this.user.id
      );
    },
    generateHealthReport(healthData) {
      return `
身高：${healthData.height} cm
体重：${healthData.weight} kg
血压：${healthData.bloodPressureSystolic}/${healthData.bloodPressureDiastolic} mmHg
心率：${healthData.heartRate} 次/分钟
血型：${healthData.bloodType}
血糖：${healthData.bloodGlucose} mmol/L
胆固醇：${healthData.cholesterol} mmol/L
甘油三酯：${healthData.triglycerides} mmol/L
肝功能：${healthData.liverFunction}
肾功能：${healthData.kidneyFunction}
其他发现：${healthData.otherFindings}
医生建议：${healthData.doctorAdvice}
分析上述各项指标，检查是否有异常指标，对每个指标做出解释（不要省略），是否合理，谢谢
`;
    },
    // 查看信息详情
    viewDetail(e) {
      this.drawer = true
      this.$nextTick(() => {
        const text = this.generateHealthReport(e);
        const chatRef = this.$refs.chat;
        chatRef.text = text;
        // chatRef.messages.push({role: "user", content: text})
        // chatRef.handleBtn();
      })

      // const id = JSON.stringify(e.id);
      // this.$router.push({
      //   path: "/user/health_detail?id=" + id,
      // });
    },
    delHealth(e) {
      this.$confirm('此操作将要删除当前健康记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        api.health.healthDelete(e.id).then(r => {
          this.$message({type: r.data.code === 200 ? 'success' : 'error', message: r.data.message, duration: 1000})
        })
      }).catch(() => {
      });

    },
    // 打开弹出框
    openDialog(action, row = null) {
      this.currentAction = action;
      if (action === "add") {
        this.dialogTitle = "添加健康档案";
        this.healthForm = {
          checkDate: null,
          height: null,
          weight: null,
          bloodPressureSystolic: null,
          bloodPressureDiastolic: null,
          heartRate: null,
          bloodType: null,
          bloodGlucose: null,
          cholesterol: null,
          triglycerides: null,
          liverFunction: null,
          kidneyFunction: null,
          otherFindings: null,
          doctorAdvice: null,
          userId: getCache('USERINFO').id,
        };
      } else if (action === "edit") {
        this.dialogTitle = "编辑健康档案";
        this.healthForm = {...row};
      }
      this.dialogVisible = true;
    },
    // 保存健康档案
    saveHealth() {
      this.$refs.healthForm.validate((valid) => {
        if (valid) {
          this.healthForm.checkDate = formatDate(this.healthForm.checkDate);
          if (this.currentAction === "add") {
            // 添加健康档案逻辑
            api.health.healthAppend(this.healthForm).then(r => {
              if (r.data.code === 200) {
                this.fetchHealth();
                this.$message.success('添加成功');
              }
            });
          } else if (this.currentAction === "edit") {
            // 编辑健康档案逻辑
            api.health.healthEditor(this.healthForm).then(r => {
              if (r.data.code === 200) {
                this.fetchHealth();
                this.$message.success('编辑成功');
              }
            });
          }
          this.dialogVisible = false;
        }
      });
    }
  }
};
</script>

<style scoped>
.health-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
  color: #303133;
}

.subtitle {
  color: #909399;
  font-size: 14px;
}

.action-buttons {
  text-align: center;
  margin-bottom: 20px;
}

.health-list {
  margin-top: 20px;
}

.health-card {
  overflow: hidden;
  transition: transform 0.3s;
  margin-bottom: 20px;
}

.health-card:hover {
  transform: translateY(-5px);
}

.health-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #ffffff;
  border-bottom: 1px solid #eaeaea;
}

.health-title {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.health-content {
  padding: 15px;
}

.health-info {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.health-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px;
}

.health-footer .el-button {
  font-size: 14px;
  color: #409eff;
}
</style>